{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KFPcBuVFw61h"
   },
   "source": [
    "# DeepLab Demo\n",
    "\n",
    "This demo will demostrate the steps to run deeplab semantic segmentation model on sample input images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "cellView": "code",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "kAbdmRmvq0Je"
   },
   "outputs": [],
   "source": [
    "#@title Imports\n",
    "\n",
    "import os\n",
    "from io import BytesIO\n",
    "import tarfile\n",
    "import tempfile\n",
    "from six.moves import urllib\n",
    "\n",
    "from matplotlib import gridspec\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "cellView": "code",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "vN0kU6NJ1Ye5"
   },
   "outputs": [],
   "source": [
    "#@title Helper methods\n",
    "\n",
    "\n",
    "class DeepLabModel(object):\n",
    "  \"\"\"Class to load deeplab model and run inference.\"\"\"\n",
    "\n",
    "  INPUT_TENSOR_NAME = 'ImageTensor:0'\n",
    "  OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'\n",
    "  INPUT_SIZE = 513\n",
    "  FROZEN_GRAPH_NAME = 'frozen_inference_graph'\n",
    "\n",
    "  def __init__(self, tarball_path):\n",
    "    \"\"\"Creates and loads pretrained deeplab model.\"\"\"\n",
    "    self.graph = tf.Graph()\n",
    "\n",
    "    graph_def = None\n",
    "    # Extract frozen graph from tar archive.\n",
    "    tar_file = tarfile.open(tarball_path)\n",
    "    for tar_info in tar_file.getmembers():\n",
    "      if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):\n",
    "        file_handle = tar_file.extractfile(tar_info)\n",
    "        graph_def = tf.GraphDef.FromString(file_handle.read())\n",
    "        break\n",
    "\n",
    "    tar_file.close()\n",
    "\n",
    "    if graph_def is None:\n",
    "      raise RuntimeError('Cannot find inference graph in tar archive.')\n",
    "\n",
    "    with self.graph.as_default():\n",
    "      tf.import_graph_def(graph_def, name='')\n",
    "\n",
    "    self.sess = tf.Session(graph=self.graph)\n",
    "\n",
    "  def run(self, image):\n",
    "    \"\"\"Runs inference on a single image.\n",
    "\n",
    "    Args:\n",
    "      image: A PIL.Image object, raw input image.\n",
    "\n",
    "    Returns:\n",
    "      resized_image: RGB image resized from original input image.\n",
    "      seg_map: Segmentation map of `resized_image`.\n",
    "    \"\"\"\n",
    "    width, height = image.size\n",
    "    resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height)\n",
    "    target_size = (int(resize_ratio * width), int(resize_ratio * height))\n",
    "    resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)\n",
    "    batch_seg_map = self.sess.run(\n",
    "        self.OUTPUT_TENSOR_NAME,\n",
    "        feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})\n",
    "    seg_map = batch_seg_map[0]\n",
    "    return resized_image, seg_map\n",
    "\n",
    "\n",
    "def create_pascal_label_colormap():\n",
    "  \"\"\"Creates a label colormap used in PASCAL VOC segmentation benchmark.\n",
    "\n",
    "  Returns:\n",
    "    A Colormap for visualizing segmentation results.\n",
    "  \"\"\"\n",
    "  colormap = np.zeros((256, 3), dtype=int)\n",
    "  ind = np.arange(256, dtype=int)\n",
    "\n",
    "  for shift in reversed(range(8)):\n",
    "    for channel in range(3):\n",
    "      colormap[:, channel] |= ((ind >> channel) & 1) << shift\n",
    "    ind >>= 3\n",
    "\n",
    "  return colormap\n",
    "\n",
    "\n",
    "def label_to_color_image(label):\n",
    "  \"\"\"Adds color defined by the dataset colormap to the label.\n",
    "\n",
    "  Args:\n",
    "    label: A 2D array with integer type, storing the segmentation label.\n",
    "\n",
    "  Returns:\n",
    "    result: A 2D array with floating type. The element of the array\n",
    "      is the color indexed by the corresponding element in the input label\n",
    "      to the PASCAL color map.\n",
    "\n",
    "  Raises:\n",
    "    ValueError: If label is not of rank 2 or its value is larger than color\n",
    "      map maximum entry.\n",
    "  \"\"\"\n",
    "  if label.ndim != 2:\n",
    "    raise ValueError('Expect 2-D input label')\n",
    "\n",
    "  colormap = create_pascal_label_colormap()\n",
    "\n",
    "  if np.max(label) >= len(colormap):\n",
    "    raise ValueError('label value too large.')\n",
    "\n",
    "  return colormap[label]\n",
    "\n",
    "\n",
    "def vis_segmentation(image, seg_map):\n",
    "  \"\"\"Visualizes input image, segmentation map and overlay view.\"\"\"\n",
    "  plt.figure(figsize=(15, 5))\n",
    "  grid_spec = gridspec.GridSpec(1, 4, width_ratios=[6, 6, 6, 1])\n",
    "\n",
    "  plt.subplot(grid_spec[0])\n",
    "  plt.imshow(image)\n",
    "  plt.axis('off')\n",
    "  plt.title('input image')\n",
    "\n",
    "  plt.subplot(grid_spec[1])\n",
    "  seg_image = label_to_color_image(seg_map).astype(np.uint8)\n",
    "  plt.imshow(seg_image)\n",
    "  plt.axis('off')\n",
    "  plt.title('segmentation map')\n",
    "\n",
    "  plt.subplot(grid_spec[2])\n",
    "  plt.imshow(image)\n",
    "  plt.imshow(seg_image, alpha=0.7)\n",
    "  plt.axis('off')\n",
    "  plt.title('segmentation overlay')\n",
    "\n",
    "  unique_labels = np.unique(seg_map)\n",
    "  ax = plt.subplot(grid_spec[3])\n",
    "  plt.imshow(\n",
    "      FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation='nearest')\n",
    "  ax.yaxis.tick_right()\n",
    "  plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])\n",
    "  plt.xticks([], [])\n",
    "  ax.tick_params(width=0.0)\n",
    "  plt.grid('off')\n",
    "  plt.show()\n",
    "\n",
    "\n",
    "LABEL_NAMES = np.asarray([\n",
    "    'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',\n",
    "    'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',\n",
    "    'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tv'\n",
    "])\n",
    "\n",
    "FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)\n",
    "FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "c4oXKmnjw6i_"
   },
   "outputs": [],
   "source": [
    "#@title Select and download models {display-mode: \"form\"}\n",
    "\n",
    "MODEL_NAME = 'mobilenetv2_coco_voctrainaug'  # @param ['mobilenetv2_coco_voctrainaug', 'mobilenetv2_coco_voctrainval', 'xception_coco_voctrainaug', 'xception_coco_voctrainval']\n",
    "\n",
    "_DOWNLOAD_URL_PREFIX = 'http://download.tensorflow.org/models/'\n",
    "_MODEL_URLS = {\n",
    "    'mobilenetv2_coco_voctrainaug':\n",
    "        'deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz',\n",
    "    'mobilenetv2_coco_voctrainval':\n",
    "        'deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz',\n",
    "    'xception_coco_voctrainaug':\n",
    "        'deeplabv3_pascal_train_aug_2018_01_04.tar.gz',\n",
    "    'xception_coco_voctrainval':\n",
    "        'deeplabv3_pascal_trainval_2018_01_04.tar.gz',\n",
    "}\n",
    "_TARBALL_NAME = 'deeplab_model.tar.gz'\n",
    "\n",
    "model_dir = tempfile.mkdtemp()\n",
    "tf.gfile.MakeDirs(model_dir)\n",
    "\n",
    "download_path = os.path.join(model_dir, _TARBALL_NAME)\n",
    "print('downloading model, this might take a while...')\n",
    "urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME],\n",
    "                   download_path)\n",
    "print('download completed! loading DeepLab model...')\n",
    "\n",
    "MODEL = DeepLabModel(download_path)\n",
    "print('model loaded successfully!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "SZst78N-4OKO"
   },
   "source": [
    "## Run on sample images\n",
    "\n",
    "Select one of sample images (leave `IMAGE_URL` empty) or feed any internet image\n",
    "url for inference.\n",
    "\n",
    "Note that we are using single scale inference in the demo for fast computation,\n",
    "so the results may slightly differ from the visualizations in\n",
    "[README](https://github.com/tensorflow/models/blob/master/research/deeplab/README.md),\n",
    "which uses multi-scale and left-right flipped inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "edGukUHXyymr"
   },
   "outputs": [],
   "source": [
    "#@title Run on sample images {display-mode: \"form\"}\n",
    "\n",
    "SAMPLE_IMAGE = 'image1'  # @param ['image1', 'image2', 'image3']\n",
    "IMAGE_URL = ''  #@param {type:\"string\"}\n",
    "\n",
    "_SAMPLE_URL = ('https://github.com/tensorflow/models/blob/master/research/'\n",
    "               'deeplab/g3doc/img/%s.jpg?raw=true')\n",
    "\n",
    "\n",
    "def run_visualization(url):\n",
    "  \"\"\"Inferences DeepLab model and visualizes result.\"\"\"\n",
    "  try:\n",
    "    f = urllib.request.urlopen(url)\n",
    "    jpeg_str = f.read()\n",
    "    original_im = Image.open(BytesIO(jpeg_str))\n",
    "  except IOError:\n",
    "    print('Cannot retrieve image. Please check url: ' + url)\n",
    "    return\n",
    "\n",
    "  print('running deeplab on image %s...' % url)\n",
    "  resized_im, seg_map = MODEL.run(original_im)\n",
    "\n",
    "  vis_segmentation(resized_im, seg_map)\n",
    "\n",
    "image_url = IMAGE_URL or _SAMPLE_URL % SAMPLE_IMAGE\n",
    "run_visualization(image_url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "7XrFNGsxzSIB"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "default_view": {},
   "name": "DeepLab Demo.ipynb",
   "provenance": [],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
